<template>
  <view class="inspection-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">日常巡检</text>
      <text class="page-subtitle">{{ deviceInfo.name }} - {{ deviceInfo.location }}</text>
    </view>

    <!-- 检查进度 -->
    <view class="progress-section">
      <view class="progress-bar">
        <view class="progress-fill" :style="{ width: inspectionProgress + '%' }"></view>
      </view>
      <view class="progress-text">
        <text>进度：{{ completedItems }}/{{ totalItems }}</text>
        <text class="progress-percent">{{ Math.round(inspectionProgress) }}%</text>
      </view>
    </view>

    <!-- 当前检查项 -->
    <view v-if="!inspectionCompleted" class="current-item-section">
      <view class="item-card">
        <view class="item-header">
          <text class="item-number">第 {{ currentItemIndex + 1 }} 项</text>
          <text class="item-name">{{ currentItem.name }}</text>
          <view class="item-category" :class="currentItem.category">{{ getCategoryText(currentItem.category) }}</view>
        </view>

        <view class="item-description">
          <text class="desc-text">{{ currentItem.description }}</text>
          <view v-if="currentItem.standard" class="item-standard">
            <text class="standard-label">检查标准：</text>
            <text class="standard-text">{{ currentItem.standard }}</text>
          </view>
        </view>

        <!-- 检查结果选择 -->
        <view class="result-selection">
          <text class="result-label">检查结果：</text>
          <view class="result-options">
            <view
              v-for="option in resultOptions"
              :key="option.value"
              class="result-option"
              :class="{ active: currentResult === option.value }"
              @click="selectResult(option.value)"
            >
              <view class="option-icon" :class="option.iconClass">{{ option.icon }}</view>
              <text class="option-text">{{ option.label }}</text>
            </view>
          </view>
        </view>

        <!-- 备注输入 -->
        <view v-if="currentResult === 'abnormal' || currentResult === 'warning'" class="notes-section">
          <text class="notes-label">问题描述：</text>
          <textarea
            v-model="currentNotes"
            placeholder="请详细描述发现的问题..."
            class="notes-input"
            auto-height
          />
        </view>

        <!-- 拍照上传 -->
        <view class="photo-section">
          <text class="photo-label">现场照片（可选）：</text>
          <view class="photo-container">
            <view
              v-for="(photo, index) in currentPhotos"
              :key="index"
              class="photo-item"
            >
              <image class="photo-image" :src="photo" mode="aspectFill" />
              <view class="photo-remove" @click="removePhoto(index)">
                <text class="remove-icon">×</text>
              </view>
            </view>
            <view v-if="currentPhotos.length < 3" class="photo-add" @click="addPhoto">
              <text class="add-icon">📷</text>
              <text class="add-text">添加照片</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button
          v-if="currentItemIndex > 0"
          class="btn btn-secondary"
          @click="previousItem"
        >
          <text class="btn-text">上一项</text>
        </button>
        <button
          class="btn btn-primary"
          @click="nextItem"
          :disabled="!canProceed"
          :class="{ 'btn-disabled': !canProceed }"
        >
          <text class="btn-text">{{ isLastItem ? '完成检查' : '下一项' }}</text>
        </button>
      </view>
    </view>

    <!-- 检查总结 -->
    <view v-else class="inspection-summary">
      <view class="summary-card">
        <view class="summary-header">
          <view class="summary-icon">✅</view>
          <view class="summary-title">检查完成</view>
        </view>

        <view class="summary-stats">
          <view class="stat-item">
            <text class="stat-number">{{ totalItems }}</text>
            <text class="stat-label">检查项</text>
          </view>
          <view class="stat-item">
            <text class="stat-number normal">{{ normalItems }}</text>
            <text class="stat-label">正常</text>
          </view>
          <view class="stat-item">
            <text class="stat-number abnormal">{{ abnormalItems }}</text>
            <text class="stat-label">异常</text>
          </view>
        </view>

        <!-- 异常项列表 -->
        <view v-if="abnormalItems > 0" class="abnormal-items">
          <view class="abnormal-header">
            <text class="abnormal-title">发现的问题</text>
            <text class="abnormal-count">{{ abnormalItems }}项</text>
          </view>
          <view
            v-for="(item, index) in abnormalResults"
            :key="index"
            class="abnormal-item"
          >
            <view class="item-info">
              <text class="item-name">{{ item.name }}</text>
              <text class="item-result">{{ item.result }}</text>
            </view>
            <text v-if="item.notes" class="item-notes">{{ item.notes }}</text>
          </view>
        </view>

        <!-- 建议操作 -->
        <view v-if="abnormalItems > 0" class="suggested-actions">
          <text class="suggestion-title">建议操作：</text>
          <view class="action-options">
            <button
              class="btn btn-primary"
              @click="createRepairWorkOrder"
            >
              <text class="btn-text">创建维修工单</text>
            </button>
            <button
              class="btn btn-secondary"
              @click="markForFollowUp"
            >
              <text class="btn-text">标记跟进</text>
            </button>
          </view>
        </view>
      </view>

      <!-- 完成操作 -->
      <view class="completion-actions">
        <button
          class="btn btn-success"
          @click="completeInspection"
        >
          <text class="btn-text">提交检查结果</text>
        </button>
        <button
          class="btn btn-secondary"
          @click="goBack"
        >
          <text class="btn-text">返回工单详情</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 页面参数
const orderId = ref('')
const deviceId = ref('')

// 设备信息
const deviceInfo = ref({
  id: '1',
  name: '移动厕所-001',
  location: '人民广场东侧'
})

// 检查项数据
const inspectionItems = ref([
  {
    id: 1,
    name: '外观清洁度检查',
    description: '检查设备外观是否清洁，无明显污渍和异味',
    category: 'cleanliness',
    standard: '外观干净整洁，无异味',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  },
  {
    id: 2,
    name: '门锁功能检查',
    description: '检查门锁是否正常开启和关闭，确保安全',
    category: 'safety',
    standard: '门锁开关顺畅，锁定可靠',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  },
  {
    id: 3,
    name: '照明系统检查',
    description: '检查内部照明是否正常亮起，亮度充足',
    category: 'functionality',
    standard: '照明正常，亮度适中',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  },
  {
    id: 4,
    name: '洗手液余量检查',
    description: '检查洗手液分配器余量是否充足',
    category: 'supplies',
    standard: '余量 > 20%',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  },
  {
    id: 5,
    name: '纸巾余量检查',
    description: '检查纸巾分配器余量是否充足',
    category: 'supplies',
    standard: '余量 > 20%',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  },
  {
    id: 6,
    name: '水箱水位检查',
    description: '检查水箱水位是否正常，无泄漏',
    category: 'functionality',
    standard: '水位正常，无漏水',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  },
  {
    id: 7,
    name: '异味检测',
    description: '检查内部是否有异常异味',
    category: 'cleanliness',
    standard: '无明显异味',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  },
  {
    id: 8,
    name: '地面清洁度',
    description: '检查地面是否清洁干燥，无积水',
    category: 'cleanliness',
    standard: '地面清洁干燥',
    result: null as string | null,
    notes: '',
    photos: [] as string[]
  }
])

// 当前检查状态
const currentItemIndex = ref(0)
const currentResult = ref<string | null>(null)
const currentNotes = ref('')
const currentPhotos = ref<string[]>([])

// 检查结果选项
const resultOptions = ref([
  {
    value: 'normal',
    label: '正常',
    icon: '✅',
    iconClass: 'normal'
  },
  {
    value: 'warning',
    label: '注意',
    icon: '⚠️',
    iconClass: 'warning'
  },
  {
    value: 'abnormal',
    label: '异常',
    icon: '❌',
    iconClass: 'abnormal'
  }
])

// 计算属性
const currentItem = computed(() => inspectionItems.value[currentItemIndex.value])
const totalItems = computed(() => inspectionItems.value.length)
const completedItems = computed(() => inspectionItems.value.filter(item => item.result !== null).length)
const inspectionProgress = computed(() => (completedItems.value / totalItems.value) * 100)
const inspectionCompleted = computed(() => completedItems.value === totalItems.value)
const isLastItem = computed(() => currentItemIndex.value === totalItems.value - 1)
const canProceed = computed(() => currentResult.value !== null)

const normalItems = computed(() => inspectionItems.value.filter(item => item.result === 'normal').length)
const abnormalItems = computed(() => inspectionItems.value.filter(item => item.result === 'abnormal').length)
const abnormalResults = computed(() => inspectionItems.value.filter(item => item.result === 'abnormal' || item.result === 'warning'))

// 获取类别文本
const getCategoryText = (category: string) => {
  const categoryMap: Record<string, string> = {
    cleanliness: '清洁',
    safety: '安全',
    functionality: '功能',
    supplies: '耗材'
  }
  return categoryMap[category] || category
}

// 选择检查结果
const selectResult = (result: string) => {
  currentResult.value = result
}

// 添加照片
const addPhoto = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['camera', 'album'],
    success: (res) => {
      if (currentPhotos.value.length < 3) {
        currentPhotos.value.push(res.tempFilePaths[0])
      }
    }
  })
}

// 移除照片
const removePhoto = (index: number) => {
  currentPhotos.value.splice(index, 1)
}

// 下一项
const nextItem = () => {
  if (!canProceed.value) return

  // 保存当前项结果
  const current = inspectionItems.value[currentItemIndex.value]
  current.result = currentResult.value
  current.notes = currentNotes.value
  current.photos = [...currentPhotos.value]

  if (isLastItem.value) {
    // 完成检查
    uni.showToast({
      title: '检查完成',
      icon: 'success'
    })
  } else {
    // 下一项
    currentItemIndex.value++
    resetCurrentState()
  }
}

// 上一项
const previousItem = () => {
  if (currentItemIndex.value > 0) {
    currentItemIndex.value--
    loadCurrentState()
  }
}

// 重置当前状态
const resetCurrentState = () => {
  const current = inspectionItems.value[currentItemIndex.value]
  currentResult.value = current.result
  currentNotes.value = current.notes
  currentPhotos.value = [...current.photos]
}

// 加载当前状态
const loadCurrentState = () => {
  resetCurrentState()
}

// 创建维修工单
const createRepairWorkOrder = () => {
  const abnormalItems = inspectionItems.value.filter(item => item.result === 'abnormal')
  const description = `日常巡检发现以下问题需要维修：\n${abnormalItems.map(item =>
    `- ${item.name}：${item.notes || '需要维修'}`
  ).join('\n')}`

  uni.navigateTo({
    url: `/pages/work-orders/create?type=repair&device_id=${deviceId.value}&description=${encodeURIComponent(description)}`
  })
}

// 标记跟进
const markForFollowUp = () => {
  uni.showModal({
    title: '标记跟进',
    content: '是否将此检查结果标记为需要后续跟进？',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '已标记跟进',
          icon: 'success'
        })
      }
    }
  })
}

// 完成检查
const completeInspection = () => {
  uni.showModal({
    title: '提交检查结果',
    content: '确定要提交检查结果吗？提交后无法修改。',
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '提交中...' })

        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          })

          // 返回工单详情页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }, 2000)
      }
    }
  })
}

// 返回
const goBack = () => {
  uni.navigateBack()
}

// 页面加载
onLoad((options) => {
  if (options?.orderId) {
    orderId.value = options.orderId
  }
  if (options?.deviceId) {
    deviceId.value = options.deviceId
  }
  console.log('检查页面加载，工单ID:', orderId.value, '设备ID:', deviceId.value)
})

// 页面挂载
onMounted(() => {
  console.log('日常检查页面加载')
  resetCurrentState()
})
</script>

<style lang="scss" scoped>
.inspection-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  padding: 24rpx;
  padding-bottom: 40rpx;
}

// 页面头部
.page-header {
  text-align: center;
  margin-bottom: 32rpx;

  .page-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }

  .page-subtitle {
    font-size: 26rpx;
    color: #666;
  }
}

// 进度区域
.progress-section {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .progress-bar {
    height: 16rpx;
    background: #e8e8e8;
    border-radius: 8rpx;
    overflow: hidden;
    margin-bottom: 16rpx;

    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #52c41a, #73d13d);
      border-radius: 8rpx;
      transition: width 0.3s ease;
    }
  }

  .progress-text {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: #666;

    .progress-percent {
      font-size: 32rpx;
      font-weight: bold;
      color: #52c41a;
    }
  }
}

// 当前检查项区域
.current-item-section {
  .item-card {
    background: #ffffff;
    border-radius: 24rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .item-header {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 24rpx;
      padding-bottom: 16rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .item-number {
        font-size: 24rpx;
        color: #999;
        background: #f8f9fa;
        padding: 8rpx 16rpx;
        border-radius: 16rpx;
      }

      .item-name {
        flex: 1;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .item-category {
        padding: 8rpx 16rpx;
        border-radius: 16rpx;
        font-size: 24rpx;
        font-weight: 500;

        &.cleanliness {
          background: #f6ffed;
          color: #52c41a;
        }

        &.safety {
          background: #fff1f0;
          color: #ff4d4f;
        }

        &.functionality {
          background: #e6f7ff;
          color: #1890ff;
        }

        &.supplies {
          background: #fff7e6;
          color: #faad14;
        }
      }
    }

    .item-description {
      margin-bottom: 32rpx;

      .desc-text {
        display: block;
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
        margin-bottom: 16rpx;
      }

      .item-standard {
        padding: 16rpx;
        background: #f8f9fa;
        border-radius: 12rpx;

        .standard-label {
          font-size: 26rpx;
          color: #666;
          font-weight: 500;
        }

        .standard-text {
          font-size: 26rpx;
          color: #333;
          margin-left: 8rpx;
        }
      }
    }

    .result-selection {
      margin-bottom: 32rpx;

      .result-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 16rpx;
      }

      .result-options {
        display: flex;
        gap: 16rpx;

        .result-option {
          flex: 1;
          padding: 24rpx 16rpx;
          background: #f8f9fa;
          border: 2rpx solid #e8e8e8;
          border-radius: 16rpx;
          text-align: center;
          transition: all 0.3s ease;

          &.active {
            transform: scale(1.05);
            box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
          }

          &.active.normal {
            background: #f6ffed;
            border-color: #52c41a;
          }

          &.active.warning {
            background: #fff7e6;
            border-color: #faad14;
          }

          &.active.abnormal {
            background: #fff1f0;
            border-color: #ff4d4f;
          }

          .option-icon {
            display: block;
            font-size: 48rpx;
            margin-bottom: 8rpx;
          }

          .option-text {
            display: block;
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
          }
        }
      }
    }

    .notes-section {
      margin-bottom: 32rpx;

      .notes-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 12rpx;
      }

      .notes-input {
        width: 100%;
        min-height: 120rpx;
        padding: 24rpx;
        border: 2rpx solid #e8e8e8;
        border-radius: 12rpx;
        font-size: 28rpx;
        background: #fafafa;
        transition: all 0.3s ease;

        &:focus {
          border-color: #52c41a;
          background: #ffffff;
          box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
        }
      }
    }

    .photo-section {
      margin-bottom: 32rpx;

      .photo-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 16rpx;
      }

      .photo-container {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;

        .photo-item {
          position: relative;
          width: 200rpx;
          height: 200rpx;
          border-radius: 12rpx;
          overflow: hidden;
          background: #f8f9fa;

          .photo-image {
            width: 100%;
            height: 100%;
          }

          .photo-remove {
            position: absolute;
            top: 8rpx;
            right: 8rpx;
            width: 40rpx;
            height: 40rpx;
            background: rgba(0, 0, 0, 0.6);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;

            .remove-icon {
              font-size: 24rpx;
              color: #ffffff;
            }
          }
        }

        .photo-add {
          width: 200rpx;
          height: 200rpx;
          border: 2rpx dashed #e8e8e8;
          border-radius: 12rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background: #fafafa;
          transition: all 0.3s ease;

          &:active {
            background: #f5f5f5;
          }

          .add-icon {
            font-size: 48rpx;
            color: #999;
            margin-bottom: 8rpx;
          }

          .add-text {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }

    .action-buttons {
      display: flex;
      gap: 16rpx;

      .btn {
        flex: 1;
        height: 88rpx;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        font-weight: 500;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.98);
        }

        .btn-text {
          font-size: 30rpx;
        }

        &.btn-primary {
          background: linear-gradient(135deg, #52c41a, #73d13d);
          color: #ffffff;
          box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

          &.btn-disabled {
            background: #ccc;
            box-shadow: none;
            transform: none;
          }
        }

        &.btn-secondary {
          background: #ffffff;
          color: #52c41a;
          border: 2rpx solid #52c41a;
        }
      }
    }
  }
}

// 检查总结
.inspection-summary {
  .summary-card {
    background: #ffffff;
    border-radius: 24rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .summary-header {
      text-align: center;
      margin-bottom: 32rpx;

      .summary-icon {
        display: block;
        font-size: 64rpx;
        margin-bottom: 16rpx;
      }

      .summary-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .summary-stats {
      display: flex;
      justify-content: space-around;
      margin-bottom: 32rpx;
      padding: 24rpx;
      background: #f8f9fa;
      border-radius: 16rpx;

      .stat-item {
        text-align: center;

        .stat-number {
          display: block;
          font-size: 40rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;

          &.normal {
            color: #52c41a;
          }

          &.abnormal {
            color: #ff4d4f;
          }
        }

        .stat-label {
          font-size: 24rpx;
          color: #666;
        }
      }
    }

    .abnormal-items {
      margin-bottom: 32rpx;

      .abnormal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .abnormal-title {
          font-size: 28rpx;
          color: #333;
          font-weight: bold;
        }

        .abnormal-count {
          font-size: 24rpx;
          color: #ff4d4f;
        }
      }

      .abnormal-item {
        padding: 20rpx;
        background: #fff1f0;
        border-left: 4rpx solid #ff4d4f;
        border-radius: 8rpx;
        margin-bottom: 12rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .item-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8rpx;

          .item-name {
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
          }

          .item-result {
            font-size: 26rpx;
            color: #ff4d4f;
            font-weight: 500;
          }
        }

        .item-notes {
          font-size: 24rpx;
          color: #666;
          line-height: 1.5;
        }
      }
    }

    .suggested-actions {
      margin-bottom: 32rpx;

      .suggestion-title {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 16rpx;
      }

      .action-options {
        display: flex;
        gap: 16rpx;

        .btn {
          flex: 1;
          height: 80rpx;
          border-radius: 16rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 28rpx;
          font-weight: 500;
          transition: all 0.3s ease;

          &:active {
            transform: scale(0.98);
          }

          .btn-text {
            font-size: 28rpx;
          }

          &.btn-primary {
            background: linear-gradient(135deg, #52c41a, #73d13d);
            color: #ffffff;
            box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);
          }

          &.btn-secondary {
            background: #ffffff;
            color: #52c41a;
            border: 2rpx solid #52c41a;
          }
        }
      }
    }
  }
}

// 完成操作
.completion-actions {
  display: flex;
  gap: 16rpx;

  .btn {
    flex: 1;
    height: 88rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    font-weight: 500;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }

    .btn-text {
      font-size: 30rpx;
    }

    &.btn-success {
      background: linear-gradient(135deg, #52c41a, #95de64);
      color: #ffffff;
      box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);
    }

    &.btn-secondary {
      background: #ffffff;
      color: #666;
      border: 2rpx solid #e8e8e8;
    }
  }
}
</style>